
function randChoice( max )
{
	return Math.floor( Math.random() * max );	
}

var maxZIndex = 100;
var _interval = 300;
var frameLastPos = null;
var _photoPrefix = 'photo_';

function Frame( cId, ancetUrl, photoUrl, container, index )
{
	function _distribute()
	{
		// Distributes x and y for container

		var dx = container.width() - _frame.width();
		var dy = container.height() - _frame.height();

		var x = randChoice( dx );
		var y = randChoice( dy );

		_frame.css( 'left', String( x ) + "px" );
		_frame.css( 'top', String( y ) + "px" );
	}


	var _frame = $( '#photo_frame_template' ).clone();

	_frame.attr( 'id', _photoPrefix + cId );	

	_frame.find( '.start-photo-caption > a' ).attr( 'href', ancetUrl );

	$( 'body' ).append( _frame );

	container.append( _frame );

	_distribute();

	_frame.draggable();

	this.getIcon = function()
	{
		// return 'fruit' icon
		return _frame.find( '[name=icon]' );
	}

	_frame.on(	'mousedown', 
				function() 
				{ 
					frameLastPos = {};

					frameLastPos.left = $( this ).css( 'left' );
					frameLastPos.top = $( this ).css( 'top' );

					$( this ).css( 'z-index', String( maxZIndex ) ); maxZIndex++; 
				} 
	);

	_frame.on(	'mouseup',
				function()
				{
					var this_ = this;
					setTimeout(
						function()
						{
							if( frameLastPos != null )
							{
								$( this_ ).animate( { 'left': frameLastPos.left, 'top': frameLastPos.top }, 500 );
								frameLastPos = null;
							}
						},
						0
					);
				}
	);

	if( photoUrl == "" )
	{
		photoUrl = "/static/img/no-photo.png";
	}

	
	_frame.find( '[name=photo]' ).css( 'background-image', "url( '" + photoUrl + "' )" );

	var _cId = cId;

	setTimeout( function() { _frame.css( 'display', "block" ); }, index * _interval );
}

// corrects position of a small square to be into a big square
function _correctRectPoses( smallRect, bigRect, smallRectPadding )
{
	// test x
	var correctX = 0;
	var correctY = 0;

	var smallRectPaddingOffset = smallRectPadding * 2;

	var randInc = randChoice( 50 );

	if( smallRect.left < bigRect.left )
	{
		correctX = bigRect.left - smallRect.left + randInc;
	}
	else
	if( smallRect.right > bigRect.right )
	{
		correctX = bigRect.right - smallRect.right - smallRectPaddingOffset - randInc;
	}

	if( smallRect.top < bigRect.top )
	{
		correctY = bigRect.top - smallRect.top + randInc;
	}
	else
	if( smallRect.bottom > bigRect.bottom )
	{
		correctY = bigRect.bottom - smallRect.bottom - smallRectPaddingOffset - randInc;
	}

	return [ correctX, correctY ];
}

function _drop( ev, ui )
{
	var draggable = $( ui.draggable );
	var dragId = draggable.attr( 'id' );
	var droppable = $( this );
	var dropId = droppable.attr( 'id' );

	var contactId = draggable.attr( 'id' ).substring( _photoPrefix.length, dragId.length );
	$( '#c_' + contactId ).attr( 'class', dropId.substring( 0, "score0".length ) );

	var dropOffset = droppable.offset();
	var dragOffset = draggable.offset();

	var smallRectPadding = draggable.css( 'padding' );
	smallRectPadding = smallRectPadding.substring( 0, smallRectPadding.indexOf( 'px' ) );					

	var correctPoses = _correctRectPoses(
		{
			'left': dragOffset.left,
			'top': dragOffset.top,
			'right': dragOffset.left + draggable.width(),
			'bottom': dragOffset.top + draggable.height()
		},
		{
			'left': dropOffset.left,
			'top': dropOffset.top,
			'right': dropOffset.left + droppable.width(),
			'bottom': dropOffset.top + droppable.height()
		},
		smallRectPadding
	);

	draggable.animate(
		{
			'left': "+=" + String( correctPoses[ 0 ] ) + "px",
			'top': "+=" + String( correctPoses[ 1 ] ) + "px"
		},
		500
	);

	frameLastPos = null; // reset it
}

function onLoadSection()
{
	setTitle( 'Контакты' );
	
	var boardContainer = $( '#board-container' );

	var animateTo = Math.max(0, ( ( $(window).width() - boardContainer.outerWidth() ) / 2) + $(window).scrollLeft()) + "px";

	$( '.droppable' ).droppable( { drop: _drop } );
	
	boardContainer.animate( 
		{ 
			left: animateTo 
		}, 
		2000, 
		function()
		{
			$.fancybox.hideLoading();			

			// show photos

			setTimeout(
				function()
				{
					$( '#continue' ).hide();
					$( '#continue' ).css( 'visibility', "visible" );
					$( '#continue' ).fadeIn( 'slow' );
				},
				_interval * 13 // 13 is a num of contacts on the page
			);

			var index = 0;

			var iconSet = false;

			function scoreEach( this_, score )
			{
				var obj = $( this_ );

				var objId = obj.attr( 'id' );

				var cId = objId.substring( 2, objId.length );
				var urls = obj.val().split( ',' );

				var photoUrl = urls[ 0 ];
				var ancetUrl = urls[ 1 ];

				var f = new Frame( cId, ancetUrl, photoUrl, $( '#score' + score + '_container' ), index );

				if( score == '1' )
				{
					// put image 'fruit' icon

					var _iconArr = [ 'apple.png', 'banana.png', 'chili.png', 'chili.png', 'melon.png', 'strawberry.png', 'orange.png' ];
					
					if( !iconSet )
					{
						if( score == '1' )
						{
							var doSetIcon = Math.random() > 0.5;

							if( doSetIcon )
							{

								var f_ = f;
	
								setTimeout(
									function()
									{
		
										var index = Math.floor( Math.random() * _iconArr.length );
										var iconUrl = "/static/img/photo-icons/" + _iconArr[ index ];
					
										var icon = f_.getIcon();
										icon.attr( 'src', iconUrl );
										icon.css( 'display', "block" );
									},
									7000
								);
	
								iconSet = true;
							}
						}						
					}
				}

				index++;
			}

			$( '.score1' ).each( function() { scoreEach( this, "1" ) } );				
			$( '.score0' ).each( function() { scoreEach( this, "0" ) } );
		}
	);
}

function onContinue( nextSection_ )
{
	var contactIdsScore = [ [], [] ];
	var classes = [ 'score0', 'score1' ];

	
	for( var i = 0; i < classes.length; i++ )
	{
		var cls = classes[ i ];
		
		$( '.' + cls ).each(
			function()
			{
				var objId = $( this ).attr( 'id' );
				var cId = objId.substring( 2, objId.length );
	
				contactIdsScore[ i ].push( cId );
			}
		);
	}

	if( contactIdsScore[ 0 ].length == 0 || contactIdsScore[ 1 ].length == 0 )
	{
		$.fancybox( $( '#minimum' ).html() );
	}
	else
	{

		ajax( 
			{
				url: '/train-switch/',
				method: "POST",
				data:
					{
						contact_ids_score0: contactIdsScore[ 0 ],
						contact_ids_score1: contactIdsScore[ 1 ]
					},
				success:
					function()
					{
						$( '#board-container' ).animate(
							{
								left: "3000px",
							},
							2000,
							function()
							{
								if( nextSection_ == null )
								{
									loader.load( 3 );
								}
								else
								{
									loader.load( nextSection_ );
								}
							}
						);
					}
			}
		);

		$.fancybox.showLoading();
	}
}

